package com.example.itboy.myapplication;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends BaseActivity {


    @BindView(R.id.textView_001)
    TextView textView001;
    @BindView(R.id.textView_002)
    TextView textView002;
    @BindView(R.id.image_view_001)
    ImageView imageView001;
    @BindView(R.id.image_view_002)
    ImageView imageView002;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }


    @OnClick({R.id.textView_001, R.id.textView_002})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.textView_001:
                applyWritePermission();

                break;
            case R.id.textView_002:
                boolean rationale = ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.CAMERA);//判断是否再次请求
                if (rationale){//再次请求
                    applyWritePermission();
                }else {
                    showPermissionDialog(this);
                }

                break;
        }
    }


    /**
     * 使用相机
     */

    int REQUEST_CAMERA=1;
    File file;
    private void useCamera() {
//        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE_SECURE);
        file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/test/" + System.currentTimeMillis() + ".jpg");
        file.getParentFile().mkdirs();

        //改变Uri  com.xykj.customview.fileprovider注意和xml中的一致
        Uri uri = FileProvider.getUriForFile(getApplicationContext(), "com.xykj.customview.fileprovider", file);
        //添加权限
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, REQUEST_CAMERA);
    }

    /**
     * 申请指定的权限.
     */
    public void applyWritePermission() {
        String[] permissions = {Manifest.permission.CAMERA};
        if (Build.VERSION.SDK_INT >= 23) {
            int check = this.checkSelfPermission(Manifest.permission.CAMERA);

            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            if (check == PackageManager.PERMISSION_GRANTED) {
                //调用相机
                useCamera();
                return;
            } else if (check==PackageManager.PERMISSION_DENIED){
                requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);
                return;
            }
        } else {
            useCamera();
        }
    }


    AlertDialog mPermissionDialog;
    /**
     *  * 不再提示权限 时的展示对话框
     */
    public void showPermissionDialog(Context mContext) {
        if (mPermissionDialog == null) {
            mPermissionDialog = new AlertDialog.Builder(mContext).setMessage("已禁用权限，请手动授予")
                    .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
//                            cancelPermissionDialog();
                            if (mPermissionDialog!=null)mPermissionDialog.cancel();
                            Uri packageURI = Uri.parse("package:" + getPackageName());
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                            startActivity(intent);
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (mPermissionDialog!=null)mPermissionDialog.cancel();
//                            cancelPermissionDialog();
                        }
                    }).create();
        }
        mPermissionDialog.show();
    }


    /**
     * 响应权限结果
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults[0]==PackageManager.PERMISSION_GRANTED){
                useCamera();
            } else {
                Toast.makeText(this, "权限被拒绝", Toast.LENGTH_SHORT).show();
                boolean rationale = ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.CAMERA);//判断是否再次请求
                if (rationale){//再次请求
                    applyWritePermission();
                }else {
                    showPermissionDialog(this);
                }
                // 没有获取 到权限，从新请求，或者关闭app
                Toast.makeText(this, "需要存储权限", Toast.LENGTH_SHORT).show();
            }
        }
    }





    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            //在手机相册中显示刚拍摄的图片
            Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri contentUri = Uri.fromFile(file);
            mediaScanIntent.setData(contentUri);
            sendBroadcast(mediaScanIntent);
            imageView002.setImageURI(Uri.fromFile(file));
        }
    }
}
